package visiopuce.action;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.hibernate.HibernateException;

import visiopuce.ICommandIds;
import visiopuce.objets.Cotation;
import visiopuce.objets.Prelevement;
import visiopuce.service.CotationServiceImpl;
import visiopuce.service.PrelevementServiceImpl;

public class CotationNonPasseeAction extends Action {

	public CotationNonPasseeAction(String text) {
		super(text);
		setId(ICommandIds.CMD_PARSER_CONSERVATION);
		setActionDefinitionId(ICommandIds.CMD_PARSER_CONSERVATION);
		setText("Enregistrer les cotations non passées");
		setToolTipText("Enregistrer les cotations non passées");
		setImageDescriptor(visiopuce.Activator.getImageDescriptor("/icons/download.png"));

	}

	public void run() {
		FileDialog dlg = new FileDialog(Display.getCurrent().getActiveShell(), SWT.OPEN);
		dlg.setText("Télécharger");
		String path = dlg.open();
		if (path != null) {
			InputStream ips;
			try {
				String ligne = null;
				ips = new FileInputStream(path);
				InputStreamReader ipsr = new InputStreamReader(ips, "utf8");
				BufferedReader br = new BufferedReader(ipsr);
				while ((ligne = br.readLine()) != null) {
					List<Prelevement> prelevements = PrelevementServiceImpl.getInstance().getPrelevementByNumSejour(ligne.trim());
					for (Prelevement prelevement : prelevements) {
						prelevement.setCotationEnvoye(1);
						PrelevementServiceImpl.getInstance().save(prelevement);
						List<Cotation> cotations = CotationServiceImpl.getInstance().getCotationByNumSejour(ligne.trim());
						for (Cotation cotation : cotations) {
							cotation.setEnvoyer(null);
							CotationServiceImpl.getInstance().save(cotation);
						}
					}

				}

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (HibernateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}